<template>
  <div class="user-register-container">
    <div class="register-card">
      <h2 class="register-title">创建新账户</h2>
      <p class="register-subtitle">加入我们，开始您的志愿者之旅</p>
      
      <form class="register-form" @submit.prevent="handleRegister">
        <!-- 用户名 -->
        <div class="form-row">
          <label for="username" class="form-label">用户名</label>
          <div class="form-input-container">
            <input 
              id="username"
              type="text" 
              v-model.trim="form.username" 
              :class="{ 'is-error': errors.username }"
              placeholder="3-20位字母或数字"
            />
            <p v-if="errors.username" class="error-message">
              <i class="icon-error"></i>{{ errors.username }}
            </p>
          </div>
        </div>

        <!-- 密码 -->
        <div class="form-row">
          <label for="password" class="form-label">密码</label>
          <div class="form-input-container">
            <input 
              id="password"
              type="password" 
              v-model.trim="form.password" 
              :class="{ 'is-error': errors.password }"
              placeholder="至少6位字符"
            />
            <p v-if="errors.password" class="error-message">
              <i class="icon-error"></i>{{ errors.password }}
            </p>
          </div>
        </div>

        <!-- 确认密码 -->
        <div class="form-row">
          <label for="confirmPassword" class="form-label">确认密码</label>
          <div class="form-input-container">
            <input 
              id="confirmPassword"
              type="password" 
              v-model.trim="form.confirmPassword" 
              :class="{ 'is-error': errors.confirmPassword }"
              placeholder="再次输入密码"
            />
            <p v-if="errors.confirmPassword" class="error-message">
              <i class="icon-error"></i>{{ errors.confirmPassword }}
            </p>
          </div>
        </div>

        <!-- 手机号 -->
        <div class="form-row">
          <label for="phone" class="form-label">手机号</label>
          <div class="form-input-container">
            <input 
              id="phone"
              type="tel" 
              v-model.trim="form.phone" 
              :class="{ 'is-error': errors.phone }"
              placeholder="11位手机号码"
            />
            <p v-if="errors.phone" class="error-message">
              <i class="icon-error"></i>{{ errors.phone }}
            </p>
          </div>
        </div>

        <!-- 邮箱 -->
        <div class="form-row">
          <label for="email" class="form-label">邮箱</label>
          <div class="form-input-container">
            <input 
              id="email"
              type="email" 
              v-model.trim="form.email" 
              :class="{ 'is-error': errors.email }"
              placeholder="example@domain.com"
            />
            <p v-if="errors.email" class="error-message">
              <i class="icon-error"></i>{{ errors.email }}
            </p>
          </div>
        </div>

        <!-- 用户角色 -->
        <div class="form-row">
          <label for="role" class="form-label">用户角色</label>
          <div class="form-input-container">
            <select 
              id="role"
              v-model="form.role" 
              :class="{ 'is-error': errors.role }"
            >
              <option value="" disabled>请选择角色</option>
              <!-- <option value="1">管理员</option> -->
              <option value="2">志愿者</option>
              <!-- <option value="3">领队</option> -->
            </select>
            <p v-if="errors.role" class="error-message">
              <i class="icon-error"></i>{{ errors.role }}
            </p>
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" :disabled="isLoading" class="register-button">
            <span v-if="isLoading" class="button-loading"></span>
            {{ isLoading ? '注册中...' : '立即注册' }}
          </button>
        </div>
      </form>

      <div class="extra-links">
        <span>已有账号？</span>
        <router-link to="/login_management" class="login-link">立即登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/utils/request';

// 表单数据
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  role: ''
});

// 错误信息
const errors = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  role: ''
});

// 加载状态
const isLoading = ref(false);

// 路由实例
const router = useRouter();

// 表单验证
const validateForm = () => {
  let isValid = true;
  
  // 重置错误信息
  Object.keys(errors).forEach(key => errors[key] = '');
  
  if (!form.username) {
    errors.username = '用户名不能为空';
    isValid = false;
  } else if (form.username.length < 3 || form.username.length > 20) {
    errors.username = '用户名长度应为3-20位';
    isValid = false;
  } else if (!/^[a-zA-Z0-9]+$/.test(form.username)) {
    errors.username = '用户名只能包含字母和数字';
    isValid = false;
  }

  if (!form.password) {
    errors.password = '密码不能为空';
    isValid = false;
  } else if (form.password.length < 6) {
    errors.password = '密码至少6位';
    isValid = false;
  } else if (!/[A-Za-z]/.test(form.password) || !/[0-9]/.test(form.password)) {
    errors.password = '密码应包含字母和数字';
    isValid = false;
  }

  if (!form.confirmPassword) {
    errors.confirmPassword = '请确认密码';
    isValid = false;
  } else if (form.confirmPassword !== form.password) {
    errors.confirmPassword = '两次输入的密码不一致';
    isValid = false;
  }

  const phoneReg = /^1[3-9]\d{9}$/;
  if (!form.phone) {
    errors.phone = '手机号不能为空';
    isValid = false;
  } else if (!phoneReg.test(form.phone)) {
    errors.phone = '请输入有效的手机号';
    isValid = false;
  }

  const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  if (!form.email) {
    errors.email = '邮箱不能为空';
    isValid = false;
  } else if (!emailReg.test(form.email)) {
    errors.email = '请输入有效的邮箱地址';
    isValid = false;
  }

  if (!form.role) {
    errors.role = '请选择用户角色';
    isValid = false;
  }

  return isValid;
};

// 注册处理
const handleRegister = async () => {
  if (!validateForm()) return;

  try {
    isLoading.value = true;
    const response = await request({
      url: '/auth-service/auth/register',
      method: 'post',
      data: {
        username: form.username,
        password: form.password,
        phone: form.phone,
        email: form.email,
        role: parseInt(form.role)
      }
    });

    if (response.code === 200) {
      alert('注册成功，请登录');
      router.push('/');
    }
  } catch (error) {
    // 错误处理已在 request.js 中完成
  } finally {
    isLoading.value = false;
  }
};
</script>

<style scoped>
.user-register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f8fafc;
  padding: 20px;
}

.register-card {
  width: 100%;
  max-width: 680px;
  background: #ffffff;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.register-card:hover {
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 8px;
  color: #2563eb;
  font-size: 24px;
  font-weight: 600;
}

.register-subtitle {
  text-align: center;
  margin-bottom: 30px;
  color: #64748b;
  font-size: 14px;
}

.form-row {
  display: flex;
  margin-bottom: 16px;
}

.form-label {
  width: 120px;
  margin-right: 20px;
  margin-bottom: 0;
  font-weight: 500;
  color: #334155;
  font-size: 14px;
  line-height: 42px;
  text-align: right;
}

.form-input-container {
  flex: 1;
}

input,
select {
  width: 100%;
  padding: 12px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.3s;
  background-color: #f8fafc;
}

select {
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%234b5563' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 12px center;
  background-size: 16px;
}

input:focus,
select:focus {
  border-color: #2563eb;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
  outline: none;
  background-color: #ffffff;
}

input.is-error,
select.is-error {
  border-color: #dc2626;
}

input.is-error:focus,
select.is-error:focus {
  box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
}

.error-message {
  display: flex;
  align-items: center;
  color: #dc2626;
  font-size: 12px;
  margin-top: 6px;
  line-height: 1.4;
}

.icon-error {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #dc2626;
  mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z'/%3E%3C/svg%3E") no-repeat center;
  margin-right: 4px;
}

.form-actions {
  margin-top: 30px;
  padding-left: 140px;
}

.register-button {
  position: relative;
  width: 100%;
  padding: 14px;
  background-color: #2563eb;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.register-button:hover:not(:disabled) {
  background-color: #1d4ed8;
  transform: translateY(-1px);
}

.register-button:active:not(:disabled) {
  transform: translateY(0);
}

.register-button:disabled {
  background-color: #e2e8f0;
  cursor: not-allowed;
}

.button-loading {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #ffffff;
  animation: spin 1s ease-in-out infinite;
  margin-right: 8px;
  vertical-align: middle;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.extra-links {
  margin-top: 24px;
  text-align: center;
  color: #64748b;
  font-size: 14px;
}

.login-link {
  color: #2563eb;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.login-link:hover {
  color: #1d4ed8;
  text-decoration: underline;
}
</style>